package pl.edu.agh.dsrg.sr.chat.communicator;

import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;

import pl.edu.agh.dsrg.sr.chat.common.MessageChanelNotificationAppender;
import pl.edu.agh.dsrg.sr.chat.protos.ChatOperationProtos.ChatMessage;

import com.google.protobuf.InvalidProtocolBufferException;

public class MessageChannelReceiver extends ReceiverAdapter {

	private MessageChanelNotificationAppender notificationAppender;
	private ChatCommunicator client;

	public MessageChannelReceiver(
			MessageChanelNotificationAppender notificationAppender,
			ChatCommunicator client) {
		super();
		this.notificationAppender = notificationAppender;
		this.client = client;
	}

	// @Override
	// public void viewAccepted(View new_view) {
	// }

	@Override
	public void receive(Message msg) {
		// System.out.println("<<<<< MessageChannelReceiver.receive()");
		if (msg.getSrc().toString().equals(client.getNick())) {
			return;
		}

		byte[] raw_stream;
		raw_stream = msg.getBuffer();
		try {
			ChatMessage chatMessage = ChatMessage.parseFrom(raw_stream);
			notificationAppender.messageReceived(chatMessage, msg.getSrc()
					.toString());
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
	}

}
